home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World Komputer 2010 April
/
PCWorld0410.iso
/
pluginy Firefox
/
14642
/
14642.xpi
/
chrome
/
content
/
history.js
< prev
next >
Wrap
Text File
|
2009-10-14
|
53KB
|
1,387 lines
/* Copyright 2009, Boomtango.com. All Rights Reserved. */
/* history.js
* Responsible for the history ui window
*/
Components.utils.import("resource://boomtango/app.js");
var bthistory = {
currView: "category",
currDur: "day",
currOffset: 0,
currTime: Date.now(),
controllers: {},
_currHash: "",
// XXX: Perhaps these helper funcitons can go into a util class
hasClass: function(ele,cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
},
addClass: function(ele,cls) {
if (!this.hasClass(ele,cls)) ele.className += " "+cls;
},
removeClass: function(ele,cls) {
if (this.hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
},
changeDeck: function(index) {
var deck = document.getElementById("btfilter_deck");
deck.selectedIndex = index;
},
onNavChanged: function(){
var calnav = document.getElementById("calnav");
this.currTime = calnav.dateValue.getTime();
this.loadView(this.currView, this.currDur);
document.getElementById("calpanel").hidePopup();
},
hideBubblePreview: function(){
this.changeDeck(0);
},
showBubblePreview: function(el, id, isTracker){
this._hoverTimer = null;
this._hoverID = id;
this._hoverShowing = true;
var panel = document.getElementById("bubble");
var dataset;
if(isTracker){
dataset = this.storage.queryTrackerByTrackerID(
parseInt(id, 10)
);
} else {
dataset = this.storage.queryTrackerByFTSRowId(
parseInt(id, 10)
);
}
var data = dataset[0];
var len = dataset.length;
var previews = [];
var thumbID = 0;
for(var x=0; x < len; x++){
var type = dataset[x].type;
if(type == "web"){
data = dataset[x];
thumbID = x;
this._previewdata = data;
}
if(this.types[type].preview){
previews.push(x);
}
}
var title = data.title;
if(len == 2){
panel.setAttribute("style",
"border-color: " +
bthistory.app.getTrackerColor(dataset[x == 0 ? 1 : 0].type) + ";");
title = dataset[x == 0 ? 1 : 0].title;
} else if (len == 1){
panel.setAttribute("style",
"border-color: " +
bthistory.app.tracker.types['web'].color + ";");
}
document.getElementById("bubble_title_label").setAttribute("value",
title);
document.getElementById("bubble_url").setAttribute("value",
data.url);
document.getElementById("bubble_url").setAttribute("href",
data.url);
var start = new Date(data.starttime);
document.getElementById("bubble_start").setAttribute("value",
bthistory.datestring(data.starttime));
document.getElementById("bubble_start").setAttribute("ftsrowid",
data.ftsrowid);
document.getElementById("bubble_start").setAttribute("starttime",
data.starttime);
document.getElementById("bubble_previous").setAttribute("vid",
data.id);
document.getElementById("bubble_remove").setAttribute("ftsid",
parseInt(id, 10));
if(data.endtime < 0){
document.getElementById("bubble_spent").setAttribute("value", "");
} else {
var timespent = data.endtime - data.starttime;
document.getElementById("bubble_spent").setAttribute("value",
bthistory.duration(timespent));
}
this.previewData = dataset;
this.buildingPreview = true;
var useThumb = previews.length == 1;
if(useThumb){
this.renderPreview(thumbID);
} else {
for(var x=0; x < previews.length; x++){
if(previews[x] == thumbID){
continue;
} else {
this.renderPreview(previews[x]);
break;
}
}
}
if(previews.length > 2){
var box = document.getElementById("bubble_previewcontrols");
while(box.firstChild){
box.removeChild(box.firstChild);
}
var column = [box, box, box];
if(previews.length > 6){
var hbox = document.createElement('hbox');
column = [document.createElement('vbox'),document.createElement('vbox'),document.createElement('vbox')];
hbox.appendChild(column[0]);
hbox.appendChild(column[1]);
hbox.appendChild(column[2]);
box.appendChild(hbox);
}
var colID = 0;
for(var x=0; x < previews.length; x++){
if(previews[x] != thumbID){
var el = document.createElement('radio');
el.setAttribute('label', this.types[dataset[previews[x]].type].name);
el.setAttribute('value', previews[x]);
column[colID].appendChild(el);
colID = (colID + 1) % column.length;
}
}
box.selectedIndex = 0;
box.setAttribute("hidden", "false");
} else {
document.getElementById("bubble_previewcontrols").
setAttribute("hidden", "true");
}
this.buildingPreview = false;
document.getElementById("btfilter_deck").selectedIndex = 1;
document.getElementById("btfilter_deck").setAttribute("hidden", "false");
},
doBubbleStart: function(){
var el = document.getElementById("bubble_start");
var ftsrowid = parseInt(el.getAttribute("ftsrowid"), 10);
var starttime = parseInt(el.getAttribute("starttime"), 10);
this.currTime = starttime;
this.loadView('calendar', 'hour', ftsrowid);
},
changePreview: function(){
var box = document.getElementById("bubble_previewcontrols");
if(!this.buildingPreview){
this.renderPreview(parseInt(box.value, 10));
}
},
renderPreview: function(previewID){
this.app.log("history::renderPreview("+previewID+")");
var data = this.previewData[previewID];
var preview = document.getElementById("bubble_preview");
while(preview.childNodes.length){
preview.removeChild(preview.firstChild);
}
if(this.tracker.types[data.type] &&
this.tracker.types[data.type].preview){
try {
this.tracker.types[data.type].preview(document, preview, data);
} catch(e) { this.app.log("error in preview for type: " + e.message + "(" + data.type + ")");}
} else {
this.tracker.types['web'].preview(document, preview, this._previewdata);
}
},
buildHoverMonitor: function(){
var box = document.getElementById("body");
var self = this;
box.addEventListener(
"dblclick",
function(e){
var node = e.target;
var id = node.getAttribute ? node.getAttribute("contentID") : null;
while(!id){
node = node.parentNode;
if(node.id == "body" || !node || !node.getAttribute){
break;
}
id = node.getAttribute("contentID")
}
if(id){
var url = self.storage.FTSIDToURL(id);
if(url.length){
if(e.metaKey){
gBrowser.addTab(url);
} else {
window.location.href = url;
}
}
}
},
false
);
box.addEventListener(
"click",
function(e){
var node = e.target;
var isTracker = false;
var id = null;
node.blur();
// first check for trackerID
id = node.getAttribute ? node.getAttribute('trackerID') : null;
while(!id){
node = node.parentNode;
if(!node || node.id == "body" || !node.getAttribute){
break;
}
id = node.getAttribute("trackerID")
}
// if no tracker, look for content id
if(!id){
node = e.target;
id = node.getAttribute ? node.getAttribute("contentID") : null;
while(!id){
node = node.parentNode;
if(!node || node.id == "body" || !node.getAttribute){
break;
}
id = node.getAttribute("contentID")
}
} else {
isTracker = true;
}
if(id){
self.showBubblePreview(node, id, isTracker);
if (this.lastSelected) {
this.lastSelected.className = this.lastSelected.className.replace(/selected/, '');
}
node.className += " selected";
this.lastSelected = node;
}
},
false
);
/*
box.addEventListener(
"mouseover",
function(e){
var node = e.target;
node.blur();
var id = node.getAttribute ? node.getAttribute("contentID") : null;
while(!id){
node = node.parentNode;
if(!node || node.id == "body" || !node.getAttribute){
break;
}
id = node.getAttribute("contentID")
}
if(id){
var closebox = document.getElementById("closebox." + id);
if (closebox) {
closebox.style.visibility = "visible";
}
}
},
false
);
box.addEventListener(
"mouseout",
function(e){
var node = e.target;
node.blur();
var id = node.getAttribute ? node.getAttribute("contentID") : null;
while(!id){
node = node.parentNode;
if(!node || node.id == "body" || !node.getAttribute){
break;
}
id = node.getAttribute("contentID")
}
if(id){
var closebox = document.getElementById("closebox." + id);
if (closebox) {
closebox.style.visibility = "hidden";
}
}
},
false
);
*/
},
handleDeleteHistoryItem: function(historyitem, id) {
if (id) {
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
var check = {value: this.app.confirmDelete}; // default the checkbox to false
if (check.value) {
var result = prompts.confirmCheck(null, this.app.getString("history.deleteprompt.title"),
this.app.getString("history.deleteprompt.text"),
this.app.getString("history.deleteprompt.ask"), check);
}
// check.value is now true if the box was checked AND OK was pressed, false if
// the box was cleared AND OK was pressed, and is the default of true if Cancel was pressed.
this.app.confirmDelete = check.value;
if (!check.value || result) {
this.storage.deleteTrackersForFTSRowId(id);
document.getElementById("messagebox_message").value ="History Item Removed";
document.getElementById("btfilter_deck").selectedIndex = 2;
this.updateView();
}
//boomtangoApp.debug("DELETE" + historyitem.id + ", " + historyitem.className);
//historyitem.parentNode.removeChild(historyitem);
//this.storage.deleteTrackersForFTSRowId(id);
}
},
scrollIntoView: function(container, node, topslop, bottomslop){
const TOPSLOP = topslop || 8;
const BOTTOMSLOP = bottomslop || 8;
const HSLOP = 8;
if(!node){
return;
}
var cdim = {
top: container.boxObject.screenY + TOPSLOP,
bottom: container.boxObject.screenY + container.boxObject.height - BOTTOMSLOP,
left: container.boxObject.screenX + HSLOP,
right: container.boxObject.screenX + container.boxObject.width - HSLOP
};
var ndim = {
top: node.boxObject.screenY,
bottom: node.boxObject.height + node.boxObject.screenY,
left: node.boxObject.screenX,
right: node.boxObject.screenX + container.boxObject.width
};
var scrollAmountX = 0;
var scrollAmountY = 0;
//dump("cdim: " + cdim.toSource() + "\n");
//dump("ndim: " + ndim.toSource() + "\n");
// check vertical
if(ndim.top >= cdim.top && ndim.bottom <= cdim.bottom){
scrollAmountY = 0;
} else if (ndim.top < cdim.top ){
scrollAmountY = ndim.top - cdim.top;
} else {
scrollAmountY = ndim.bottom - cdim.bottom;
}
// check horizontal
if(ndim.left >= cdim.left && ndim.right <= cdim.right){
scrollAmountX = 0;
} else if (ndim.left < cdim.left ){
scrollAmountX = ndim.left - cdim.left;
} else {
scrollAmountX = ndim.right - cdim.right;
}
// if we need to scroll, do it
if(scrollAmountX || scrollAmountY){
var scroll = container.boxObject.QueryInterface(Components.interfaces.nsIScrollBoxObject);
scroll.scrollBy(scrollAmountX, scrollAmountY);
}
},
selectNode: function(node){
var id;
var isTracker = false;
id = node.getAttribute('trackerID');
if(id){
isTracker = true;
} else {
id = node.getAttribute('contentID');
}
var sels = document.getElementsByClassName('selected');
var len = sels.length
for(var x = 0; x < len; x++){
sels[x].className = sels[x].className.replace(/selected/,'');
}
node.className += " selected";
this.showBubblePreview(node, id, isTracker);
},
doRemove: function(elid){
var ftsrowid = parseInt(document.getElementById(elid).getAttribute('ftsid'));
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
var check = {value: this.app.confirmDelete}; // default the checkbox to false
if (check.value) {
var result = prompts.confirmCheck(null, this.app.getString("history.deleteprompt.title"),
this.app.getString("history.deleteprompt.text"),
this.app.getString("history.deleteprompt.ask"), check);
}
// check.value is now true if the box was checked AND OK was pressed, false if
// the box was cleared AND OK was pressed, and is the default of true if Cancel was pressed.
this.app.confirmDelete = check.value;
if (!check.value || result) {
this.storage.deleteTrackersForFTSRowId(ftsrowid);
document.getElementById("messagebox_message").value ="History Item Removed";
document.getElementById("btfilter_deck").selectedIndex = 2;
this.updateView();
}
},
doVisits: function(elid){
this.currVisitID = parseInt(document.getElementById(elid).getAttribute('vid'));
this.resetFilter();
this.currOrder = 'starttime';
this.currOrderDesc = true;
this.currOffset = 0;
this.currResultType = "visits";
this.loadView("results", this.currDur);
},
doThumbnail: function(){
this.currOffset = 0;
this.loadView('thumbnail', bthistory.currDur);
},
doSearch: function(){
var query = document.getElementById("query").value;
this.resetFilter();
this.currQuery = query;
this.currOrder = 'starttime';
this.currOrderDesc = true;
this.currOffset = 0;
this.currResultType = "search";
this.loadView("results", this.currDur);
},
buildSearchBox: function(){
var tb = document.getElementById("query");
tb.style.border = "none";
tb.style.fontSize = "20px";
tb.style.color = "#333";
},
onTypeBox: function(e){
if(e.target.tagName == "checkbox"){
document.getElementById("filtertype").selectedIndex = 1;
}
},
buildTypes: function(){
var box = document.getElementById("typebox");
var types = box.getElementsByTagName("checkbox");
var len = types.length;
var result = [];
if(document.getElementById("filtertype").selectedIndex != 0){
for(var x = 0; x < len; x++){
var item = types[x];
//
//if(item.hasAttribute("checked")){
if(item.checked){
var a = item.id.split('.');
result.push(a.slice(1).join('.'));
}
}
}
if(!result.length){
result.push("web");
}
return result;
},
buildTypeBox: function(){
var types = this.tracker.types;
var box = document.getElementById("typebox");
var self = this;
box.addEventListener(
"click",
function(e){
self.onTypeBox(e);
},
false
);
this.types = this.tracker.types;
var columns = [document.createElement('vbox'), document.createElement('vbox')];
while(box.childNodes.length){
box.removeChild(box.firstChild);
}
var colbox = document.createElement('hbox');
for(var x = 0; x < columns.length; x++){
colbox.appendChild(columns[x]);
}
box.appendChild(colbox);
var curCol = 0;
for(var x in types){
if(types.hasOwnProperty(x) && x != "web" && this.app.getTrackerEnabled(x)){
var cb = document.createElement("checkbox");
cb.setAttribute("label", types[x].name_plural);
cb.id = "type." + x;
columns[curCol].appendChild(cb);
curCol = (curCol + 1) % columns.length;
}
}
},
doc: document,
observe: function(subject, topic, data){
this.app.log("history::observe (" + topic + ")");
if(topic == "boomtango-visit-change"){
var ftsrowid = parseInt(data);
var dataset = this.storage.queryTrackerByFTSRowId(ftsrowid);
this.controllers[this.currView].onHistoryChange(dataset);
} else if(topic == "boomtango-refreshviews"){
this.updateView();
} else if(topic == "boomtango-visit-add"){
var ftsrowid = parseInt(data);
var dataset = this.storage.queryTrackerByFTSRowId(ftsrowid);
this.controllers[this.currView].onHistoryAdd(dataset);
} else if(topic == "boomtango-tracker-remove"){
var node = this.doc.getElementById("type." + data);
if(node){
node.parentNode.removeChild(node);
}
this.updateView();
} else if(topic == "boomtango-tracker-add"){
var types = this.types;
var box = document.getElementById("typebox");
var columns = box.getElementsByTagName("vbox");
var minCol = null;
var len = columns.length;
while(len--){
if(!minCol || minCol.childNodes.length >= columns[len].childNodes.length){
minCol = columns[len];
}
}
var cb = document.createElement("checkbox");
cb.setAttribute("label", types[data].name_plural);
cb.id = "type." + data;
minCol.appendChild(cb);
this.updateView();
}
},
onUnload: function(){
var os = Components.classes["@mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService);
os.removeObserver(this, "boomtango-refreshviews");
os.removeObserver(this, "boomtango-visit-change");
os.removeObserver(this, "boomtango-visit-add");
os.removeObserver(this, "boomtango-tracker-add");
os.removeObserver(this, "boomtango-tracker-remove");
},
resetFilter: function(){
document.getElementById("searchfromcb").checked = false;
document.getElementById("searchtocb").checked = false;
document.getElementById("filter_text").value = "";
document.getElementById("filtertype").selectedIndex = 0;
var types = this.tracker.types;
for(var x in types){
if(types.hasOwnProperty(x) && x != "web"){
var cb = document.getElementById("type." + x);
if(cb){
cb.setAttribute('checked', 'false');
}
}
}
},
handleKeyPress: function(e){
// let's cache this stuff
if(!this._keys){
this._keys = {
c: this.app.getString("hotkeys.calendarview").charCodeAt(0),
g: this.app.getString("hotkeys.categoryview").charCodeAt(0),
s: this.app.getString("hotkeys.summaryview").charCodeAt(0),
q: this.app.getString("hotkeys.query").charCodeAt(0),
h: this.app.getString("hotkeys.hour").charCodeAt(0),
d: this.app.getString("hotkeys.day").charCodeAt(0),
w: this.app.getString("hotkeys.week").charCodeAt(0),
m: this.app.getString("hotkeys.month").charCodeAt(0),
n: this.app.getString("hotkeys.next").charCodeAt(0),
p: this.app.getString("hotkeys.previous").charCodeAt(0),
t: this.app.getString("hotkeys.today").charCodeAt(0),
k: this.app.getString("hotkeys.up").charCodeAt(0),
j: this.app.getString("hotkeys.down").charCodeAt(0),
};
}
// check for return key in query
if(document.activeElement.id == "query" && e.keyCode == 13){
this.doSearch();
}
if(document.activeElement.id == "btfilter_text" && e.keyCode == 13){
this.updateFromFilter();
}
if(document.activeElement.id != "query" && document.activeElement.id != "btfilter_text"){
switch(e.keyCode){
case 37: // left arrow
this.goPrevious();
return;
case 39: // right arrow
this.goNext();
return;
case 38: // up arrow
this.controllers[this.currView].handleUpArrow();
return;
case 40: // down arrow
this.controllers[this.currView].handleDownArrow();
return;
}
switch(e.charCode){
case this._keys['q']:
document.getElementById("query").focus();
break;
case this._keys['c']:
this.loadView("calendar", this.currDur);
break;
case this._keys['g']:
this.loadView("category", this.currDur);
break;
case this._keys['s']:
this.loadView("piechart", this.currDur);
break;
case this._keys['h']:
this.loadView(this.currView, 'hour');
break;
case this._keys['d']:
this.loadView(this.currView, 'day');
break;
case this._keys['w']:
this.loadView(this.currView, 'week');
break;
case this._keys['m']:
this.loadView(this.currView, 'month');
break;
case this._keys['n']:
this.goNext();
break;
case this._keys['p']:
this.goPrevious();
break;
case this._keys['t']:
this.goToday();
break;
case this._keys['k']:
this.controllers[this.currView].handleUpArrow();
break;
case this._keys['j']:
this.controllers[this.currView].handleDownArrow();
break;
}
}
},
resizeToWindow: function(tellControllers){
var winx = document.getElementById("boomtangoHistory");
var win = {
h: winx.boxObject.height,
w: winx.boxObject.width,
x: 0,
y: 0
};
var body = document.getElementById("body");
var box = {
h: body.boxObject.height,
w: body.boxObject.width,
x: body.boxObject.x,
y: body.boxObject.y
};
this.app.debug("win: " + win.toSource() + "\n");
this.app.debug("box: " + box.toSource() + "\n");
var height = Math.max(win.h - box.y, 40);
this.app.debug("h: " + height + "\n");
body.setAttribute('height', height);
if(tellControllers){
this.controllers[this.currView].handleResize();
}
},
goHome: function(){
// move it to the start of an hour
var now = new Date();
var startOfHour = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
now.getHours()
);
this.currTime = startOfHour.getTime();
this.loadView('category', 'hour' );
},
onLoad: function(){
this.app = boomtangoApp;
this.app.log("history::load");
this.storage = this.app.storage;
this.tracker = this.app.tracker;
this.currView = this.app.historyView;
this.currDur = this.app.historyDur;
if(!this.app.showdonate){
document.getElementById("donate").setAttribute('hidden', 'true');
}
this.buildSearchBox();
this.buildTypeBox();
this.buildHoverMonitor();
var self = this;
window.addEventListener(
"keypress",
function(e){
self.handleKeyPress(e);
},
true
);
window.addEventListener(
"resize",
function(e){
self.resizeToWindow(true);
},
false
);
document.getElementById("query").focus();
this._boxwidth = document.getElementById("body").boxObject.width;
this._filterwidth = document.getElementById("btfilter").boxObject.width;
this.resizeToWindow(false);
// move it to the start of an hour
var now = new Date(this.currTime);
var startOfHour = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
now.getHours()
);
var os = Components.classes["@mozilla.org/observer-service;1"].
getService(Components.interfaces.nsIObserverService);
os.addObserver(this, "boomtango-refreshviews", false);
os.addObserver(this, "boomtango-visit-change", false);
os.addObserver(this, "boomtango-visit-add", false);
os.addObserver(this, "boomtango-tracker-add", false);
os.addObserver(this, "boomtango-tracker-remove", false);
this.updateView();
this.monitorHash();
},
monitorHash: function(){
var self = this;
window.setInterval(
function(){
var orighash = window.location.hash.substring(1);
var hash = orighash.replace(/\ /g, '%20').replace(/\+/g, '%2B');
if(self._currHash != hash){
self.updateView();
}
},
500
);
},
updateFromFilter: function(){
this.app.log("history::updateFromFilter");
this.loadView(this.currView, this.currDur);
},
updateView: function(){
var hash = window.location.hash.substring(1);
this.app.log("history::updateView");
this.app.debug(" hash=" + hash);
if(hash.length){
var a = hash.split('&');
var obj = {};
var len = a.length;
for(var x = 0; x < len; x++){
var i = a[x].split('=');
obj[i[0]] = i[1];
}
if(obj.hasOwnProperty('view')){
this.currView = obj['view'];
}
if(obj.hasOwnProperty('dur')){
this.currDur = obj['dur'];
}
if(obj.hasOwnProperty('time')){
this.currTime = parseInt(obj['time']);
}
if(obj.hasOwnProperty('starttime')){
document.getElementById('searchfromcb').checked = true;
document.getElementById("searchfrom").dateValue = new Date(parseInt(obj['starttime']));
}
if(obj.hasOwnProperty('endtime')){
document.getElementById('searchtocb').checked = true;
document.getElementById("searchto").dateValue = new Date(parseInt(obj['endtime']));
}
if(obj.hasOwnProperty('type')){
this.currResultType = obj['type'];
}
if(obj.hasOwnProperty('mtype')){
this.currMoreType = obj['mtype'];
}
if(obj.hasOwnProperty('vid')){
this.currVisitID = obj['vid'];
}
if(obj.hasOwnProperty('order')){
this.currOrder = obj['order'];
}
if(obj.hasOwnProperty('desc')){
this.currOrderDesc = parseInt(obj['desc']) != 0;
}
if(obj.hasOwnProperty('offset')){
this.currOffset = parseInt(obj['offset']);
} else {
this.currOffset = 0;
}
if(obj.hasOwnProperty('query')){
this.currQuery = decodeURIComponent(obj['query']);
document.getElementById("query").value = this.currQuery;
}
if(obj.hasOwnProperty('filter')){
document.getElementById("filter_text").setAttribute("value",
decodeURIComponent(obj['filter']));
}
if(obj.hasOwnProperty('types')){
var a = obj['types'].split(';');
var types = this.app.tracker.types;
var hasCheck = false;
for(var x in types){
if(types.hasOwnProperty(x) && x != "web" && this.app.getTrackerEnabled(x)){
var cb = document.getElementById("type." + x);
if(cb){
cb.checked = false;
}
}
}
for(var x = 0; x < a.length; x++){
if(types.hasOwnProperty(a[x]) && a[x] != "web"){
var cb = document.getElementById("type." + a[x]);
if(cb){
hasCheck = true;
cb.checked = true;
}
}
}
document.getElementById("filtertype").selectedIndex = hasCheck ? 1 : 0;
}
}
this._currHash = hash;
this.loadView(this.currView, this.currDur);
},
ONEMINUTE: 60 * 1000,
ONEHOUR: 60 * 60 * 1000,
ONEDAY: 24 * 60 * 60 * 1000,
ONEWEEK: 7 * 24 * 60 * 60 * 1000,
_dayLabel: function(currTime){
var now = Date.now();
if(currTime < now){
//check for today
var startOfDay = this._durHelper['day'].getStart(now);
if(currTime >= startOfDay){
return bthistory.app.getString("date.today");
}
var startOfYesterday = this._durHelper['day'].getStart(
now - this.ONEDAY);
if(currTime >= startOfYesterday){
return bthistory.app.getString("date.yesterday");
}
var startOfWeek = this._durHelper['week'].getStart(now);
if(currTime >= startOfWeek){
var d = new Date(currTime);
return bthistory.app.getString("date.day." + d.getDay());
}
startOfWeek = this._durHelper['week'].getStart(now - this.ONEWEEK);
if(currTime >= startOfWeek){
var d = new Date(currTime);
return bthistory.app.getString("date.lastday." + d.getDay());
}
} else {
//check for today
var endOfDay = this._durHelper['day'].getStart(now + this.ONEDAY);
if(currTime < endOfDay){
return bthistory.app.getString("date.today");
}
//check for tomorrow
var endOfTomorrow = this._durHelper['day'].getStart(
now + (this.ONEDAY * 2));
if(currTime < endOfTomorrow ){
return bthistory.app.getString("date.tomorrow");
}
var endOfWeek = this._durHelper['week'].getStart(now + this.ONEWEEK);
if(currTime < endOfWeek){
var d = new Date(currTime);
return bthistory.app.getString("date.day." + d.getDay());
}
endOfWeek = this._durHelper['week'].getStart(now + (this.ONEWEEK * 2));
if(currTime < endOfWeek){
var d = new Date(currTime);
return bthistory.app.getString("date.nextday." + d.getDay());
}
}
var d = new Date(currTime);
return d.toLocaleDateString();
},
_durHelper: {
hour: {
nextStart: function(currTime){
return currTime + bthistory.ONEHOUR;
},
prevStart: function(currTime){
return currTime - bthistory.ONEHOUR;
},
getRangeLabel: function(currTime){
var d = new Date(currTime);
return d.toLocaleDateString();
},
getLabel: function(currTime){
var label = bthistory._dayLabel(currTime);
var now = new Date(currTime);
var d = new Date(this.getStart(currTime));
if(now.toLocaleDateString() == label){
return d.toLocaleFormat(
boomtangoApp.getString("hour.format")
);
} else {
return label + ", " + d.toLocaleFormat(
boomtangoApp.getString("hour.format"));
}
},
getStart: function(currTime){
var now = new Date(currTime);
var startOfDay = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
now.getHours(),
0
);
return startOfDay.getTime();
},
getRange: function(currTime){
var now = new Date(currTime);
var startTime = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
now.getHours(),
0
);
return {
start: startTime.getTime(),
end: startTime.getTime() + bthistory.ONEHOUR
};
}
},
day: {
nextStart: function(currTime){
return currTime + bthistory.ONEDAY;
},
prevStart: function(currTime){
return currTime - bthistory.ONEDAY;
},
getRangeLabel: function(currTime){
var d = new Date(currTime);
return d.toLocaleDateString();
},
getLabel: function(currTime){
return bthistory._dayLabel(currTime);
},
getStart: function(currTime){
var now = new Date(currTime);
var startOfDay = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate()
);
return startOfDay.getTime();
},
getRange: function(currTime){
var start = this.getStart(currTime);
return {
start: start,
end: start + bthistory.ONEDAY
};
}
},
week: {
nextStart: function(currTime){
return currTime + bthistory.ONEWEEK;
},
prevStart: function(currTime){
return currTime - bthistory.ONEWEEK;
},
getRangeLabel: function(currTime){
// cheat so we don't recalculate this
if(bthistory._rangetime == currTime){
var range = bthistory._range;
} else {
var range = this.getRange(currTime);
}
var start = new Date(range.start);
var end = new Date(range.end - 1);
return start.toLocaleDateString() + " - " +
end.toLocaleDateString();
},
getLabel: function(currTime){
var now = new Date();
if(now > currTime){
var start = this.getStart(now);
if(currTime >= start){
return bthistory.app.getString("date.thisweek");
}
start = this.getStart(now - bthistory.ONEWEEK);
if(currTime >= start){
return bthistory.app.getString("date.lastweek");
}
} else {
var end = this.getStart(now + bthistory.ONEWEEK);
if(currTime < end){
return bthistory.app.getString("date.thisweek");
}
end = this.getStart(now + (bthistory.ONEWEEK * 2));
if(currTime < end){
return bthistory.app.getString("date.nextweek");
}
}
var start = this.getStart(currTime);
var d = new Date(start);
return bthistory.app.getString("date.weekstarting") + " " +
d.toLocaleDateString();
},
getStart: function(currTime){
var now = new Date(currTime);
var startOfDay = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate()
);
return startOfDay.getTime() -
(startOfDay.getDay() * bthistory.ONEDAY);
},
getRange: function(currTime){
var start = this.getStart(currTime);
return {
start: start,
end: start+ bthistory.ONEWEEK
};
}
},
month: {
nextStart: function(currTime){
var d = new Date(currTime);
if(d.getMonth == 11){
var next = new Date(
d.getFullYear() + 1,
0,
d.getDate()
);
return next.getTime();
}
var next = new Date(
d.getFullYear(),
d.getMonth() + 1,
d.getDate()
);
return next.getTime();
},
prevStart: function(currTime){
var d = new Date(currTime);
if(d.getMonth == 0){
var next = new Date(
d.getFullYear() - 1,
11,
d.getDate()
);
return next.getTime();
}
var next = new Date(
d.getFullYear(),
d.getMonth() - 1,
d.getDate()
);
return next.getTime();
},
getRangeLabel: function(currTime){
return "";
},
getLabel: function(currTime){
var d = new Date(currTime);
return d.toLocaleFormat("%B") + ", " + d.getFullYear();
},
_isLeapYear: function(currTime){
var now = new Date(currTime);
return now.getFullYear() % 4 == 0;
},
_daysInMonth: function(currTime){
var now = new Date(currTime);
var currMonth = now.getMonth();
switch(currMonth){
case 5:
case 3:
case 8:
case 10:
return 30;
case 1:
return this._isLeapYear() ? 29 : 28;
default:
return 31;
}
},
getStart: function(currTime){
var now = new Date(currTime);
var startOfMonth = new Date(
now.getFullYear(),
now.getMonth(),
1
);
return startOfMonth.getTime();
},
getRange: function(currTime){
var start = this.getStart(currTime);
return {
start: start,
end: start +
( this._daysInMonth(currTime) * bthistory.ONEDAY)
};
}
},
},
goToday: function(){
this.currTime = Date.now();
this.currOffset = 0;
this.loadView(this.currView, this.currDur);
},
changeRange: function(dur){
this.currOffset = 0;
this.loadView(this.currView, dur);
},
goNext: function(){
this.currTime = this._durHelper[this.currDur].nextStart(this.currTime);
this.currOffset = 0;
this.loadView(this.currView, this.currDur);
},
goPrevious: function(){
this.currTime = this._durHelper[this.currDur].prevStart(this.currTime);
this.currOffset = 0;
this.loadView(this.currView, this.currDur);
},
loadTitle: function(view, dur){
if(view == "results"){
switch (this.currResultType){
case 'search':
var q = this.currQuery;
if(!q || !q.length){
q = " ";
}
document.getElementById("datetimetitle").value =
this.app.getString("results.title", q);
break;
case 'more':
var rangelabel = this._durHelper[dur].getRangeLabel(this.currTime);
document.getElementById("datetimetitle").value =
this.app.getString(
"results.moretitle",
this.app.tracker.types[this.currMoreType].name_plural,
this._durHelper[dur].getLabel(this.currTime) +
(rangelabel ? ", " : "") + rangelabel
);
break;
case 'visits':
document.getElementById("datetimetitle").value =
this.app.getString("results.visittitle",
this.app.storage.IDToTitle(this.currVisitID));
break;
}
} else {
var d = new Date(this.currTime);
var rangelabel = this._durHelper[dur].getRangeLabel(this.currTime);
var timelabel = this._durHelper[dur].getLabel(this.currTime);
if(timelabel.length && rangelabel != timelabel){
document.getElementById("datetimetitle").value =
timelabel + (rangelabel ? ", " : "") + rangelabel;
} else {
document.getElementById("datetimetitle").value = rangelabel;
}
}
},
resetHash: function(){
var hash = "#view="+ this.currView +
"&dur="+ this.currDur + "&time=" + this.currTime;
if(this.currView == "results"){
hash += "&type=" + this.currResultType;
switch(this.currResultType){
case 'search':
hash += "&query=" + encodeURIComponent(this.currQuery);
if(document.getElementById('searchfromcb').checked){
var d = document.getElementById("searchfrom");
hash += "&starttime=" + d.dateValue.getTime();
}
if(document.getElementById('searchtocb').checked){
var d = document.getElementById("searchto");
hash += "&endtime=" + d.dateValue.getTime();
}
break;
case 'more':
hash += "&mtype=" + this.currMoreType;
break;
case 'visits':
hash += "&vid=" + this.currVisitID;
break;
}
hash += "&order=" + this.currOrder;
hash += "&offset=" + this.currOffset;
hash += "&desc=" + (this.currOrderDesc ? "1" : "0");
hash += "&types=" + this.currTypes.join(";");
} else {
if(this.currView == 'thumbnail'){
hash += "&offset=" + this.currOffset;
}
hash += "&types=" + this.currTypes.join(";");
if(this.currFilter && this.currFilter.length){
hash += "&filter= " + encodeURIComponent(this.currFilter);
}
}
window.location.hash = hash;
this._currHash = hash.substring(1);
},
loadView: function(view, dur, selectID){
var d = new Date(this.currTime);
this._rangetime = this.currTime;
this._range = this._durHelper[dur].getRange(this.currTime);
this.loadTitle(view, dur);
this.hideBubblePreview();
this.removeClass(document.getElementById("category"), "controlselected");
this.removeClass(document.getElementById("thumbnail"), "controlselected");
this.removeClass(document.getElementById("calendar"), "controlselected");
this.removeClass(document.getElementById("piechart"), "controlselected");
this.removeClass(document.getElementById("results"), "controlselected");
var viewEl = document.getElementById(view);
this.addClass(viewEl, "controlselected");
document.getElementById("hour.check").style.display = "none";
document.getElementById("day.check").style.display = "none";
document.getElementById("week.check").style.display = "none";
document.getElementById("month.check").style.display = "none";
document.getElementById("hour").className = "";
document.getElementById("day").className = "";
document.getElementById("week").className = "";
document.getElementById("month").className = "";
document.getElementById(dur + ".check").style.display = "block";
document.getElementById(dur).className = "current";
document.getElementById("filter_box").setAttribute("hidden", "false");
document.getElementById("searchdate_box").setAttribute("hidden", "true");
document.getElementById("results").setAttribute("hidden", view != "results");
var bodyheader = document.getElementById("body_header");
bodyheader.setAttribute("hidden", "true");
var len = bodyheader.childNodes.length;
while(len--){
bodyheader.removeChild(bodyheader.childNodes[len]);
}
this.currView = view;
this.currDur = dur;
this.app.log("history::"+view);
var body = document.getElementById("body");
body.setAttribute("width", "");
body.setAttribute("style", "");
document.getElementById("btfilter_deck").setAttribute("hidden", "false");
document.getElementById("duration_control").setAttribute("hidden", "false");
document.getElementById("gotoday").setAttribute("hidden", "false");
document.getElementById("gotodate").setAttribute("hidden", "false");
var len = body.childNodes.length;
while(len--){
body.removeChild(body.childNodes[len]);
}
this.currTypes = this.buildTypes();
this.currFilter = document.getElementById("filter_text").value;
this.resetHash();
this._data = this.controllers[view].queryTracker(this.currTypes, this.currFilter);
this.controllers[view].loadView(selectID);
},
handleMoreItems: function(type){
this.app.log("history::handleMoreItems (" + type + ")");
this.currOrder = 'starttime';
this.currOrderDesc = true;
this.currOffset = 0;
this.currResultType = "more";
this.currMoreType = type;
this.loadView("results", this.currDur);
},
datestring: function(d){
var label = bthistory._dayLabel(d);
var date = new Date(d);
return label + ", " + date.toLocaleTimeString();
},
duration: function(d){
if(d <= 0){
return " ";
}
var days = 0;
var hours = 0;
var mins = 0;
var secs = 0;
if(d > this.ONEDAY){
days = Math.floor(d / this.ONEDAY);
d = d % this.ONEDAY;
}
if(d > this.ONEHOUR){
hours = Math.floor(d / this.ONEHOUR);
d = d % this.ONEHOUR;
}
if(d > this.ONEMINUTE){
mins = Math.floor(d /this.ONEMINUTE);
d = d % this.ONEMINUTE;
}
secs = Math.floor(d / 1000);
if(days > 0){
return this.app.getString("history.duration.days", days, hours, mins, secs);
} else if (hours > 0){
return this.app.getString("history.duration.hours", hours, mins, secs);
} else if (mins > 0){
return this.app.getString("history.duration.min", mins, secs);
}
if(!secs){
return " ";
}
return this.app.getString("history.duration.secs", secs);
},
doCreateCategory: function() {
window.openDialog("chrome://boomtango/content/createCategory.xul", "",
"chrome, dialog, modal").focus();
},
doHotkeys: function(){
window.openDialog('chrome://boomtango/content/hotkeys.xul', 'hotkeysDlg', 'dialog=yes,resize=no,toolbar,centerscreen').focus();
},
doSettings: function(){
window.openDialog('chrome://boomtango/content/settings.xul', 'settingsDlg', 'dialog=yes,resize=no,toolbar,centerscreen').focus();
}
};